package cn.virens.common.util.core.stream;

import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.net.url.UrlBuilder;
import org.dromara.hutool.http.HttpUtil;
import org.dromara.hutool.http.client.HttpDownloader;
import org.dromara.hutool.http.client.Response;
import org.dromara.hutool.http.client.engine.ClientEngine;
import org.dromara.hutool.http.client.engine.ClientEngineFactory;

public class DownloaderUtil {
    /**
     * 下载成字节数组
     *
     * @param url    请求连接
     * @param engine 执行实例
     */
    public static byte[] downBytes(String url, ClientEngine engine) {
        Response response = HttpUtil.createGet(url).send(engine);
        try {
            if (response != null && response.isOk()) {
                return response.bodyBytes();
            }
        } finally {
            IoUtil.closeQuietly(response);
        }

        return null;
    }

    /**
     * 下载成字节数组
     *
     * @param url 请求连接
     */
    public static byte[] downBytes(String url) {
        return downBytes(url, ClientEngineFactory.getEngine());
    }

    public static HttpDownloader of(UrlBuilder builder) {
        return new HttpDownloader(builder.build());
    }

    public static HttpDownloader of(String url) {
        return new HttpDownloader(url);
    }

}
